<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>敏感词检测系统</title>
    <link th:href="@{/static/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/static/css/style.css}" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8 custom-col-width">
                <div class="card">
                    <div class="card-header">
                        <h3 class="mb-0 page-title text-center">敏感词检测系统</h3>
                    </div>
                    <div class="card-body">
                        <!-- 文件上传区域 -->
                        <div class="upload-area mb-4" id="dropZone">
                            <div class="text-center p-5 border rounded">
                                <h5>拖拽文件到此处或点击选择文件</h5>
                                <p class="text-muted">支持的文件格式：TXT、Word、Excel、PPT、PDF</p>
                                <input type="file" id="fileInput" multiple style="display: none">
                                <button class="btn btn-primary" onclick="document.getElementById('fileInput').click()">
                                    选择文件
                                </button>
                            </div>
                        </div>
                        <div class="row justify-content-center mb-4">
                            <div class="col-md-12">
                                <div class="alert alert-info px-4 py-3 text-start" style="font-size: 0.92rem; line-height: 1.7;">
                                    <strong class="mb-2 d-block" style="font-size:1.02rem;">使用建议：</strong>
                                    <ol class="mb-0 ps-3" style="list-style-type: decimal;">
                                        <li>WPS专有格式（<code>.wps</code>、<code>.dpt</code>、<code>.et</code>）目前无法识别，请先在WPS中将文件另存为Office兼容格式（如<code>.docx</code>、<code>.xlsx</code>、<code>.pptx</code>）后再上传检测。</li>
                                        <li>如果另存为Office兼容格式后仍无法识别，建议将文件另存为<code>PDF</code>格式后再上传检测。</li>
                                    </ol>
                                </div>
                            </div>
                        </div>

                        <!-- 文件列表 -->
                        <div id="fileList" class="mb-4" style="display: none;">
                            <h5 class="d-flex justify-content-between align-items-center mb-3">
                                <span>已选择的文件：</span>
                                <button class="btn btn-sm btn-outline-danger" onclick="clearAllFiles()">
                                    一键清除
                                </button>
                            </h5>
                            <ul class="list-group" id="selectedFiles"></ul>
                        </div>

                        <!-- 检测按钮和模式切换 -->
                        <div class="text-center d-flex justify-content-center align-items-center">
                            <button class="btn btn-primary me-3" id="detectBtn" disabled onclick="detectFiles()">
                                开始检测
                            </button>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="detectMode" id="modeExact" value="exact" checked>
                                <label class="form-check-label" for="modeExact">精确检测</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="detectMode" id="modeFuzzy" value="fuzzy">
                                <label class="form-check-label" for="modeFuzzy">模糊检测</label>
                            </div>
                            <button type="button" class="btn btn-link p-0 ms-2" id="modeHelpBtn" data-bs-toggle="popover" data-bs-placement="right" data-bs-trigger="focus" title="检测模式说明" data-bs-content="精确检测：仅当文档内容与敏感词完全一致时才判定为命中。<br/>模糊检测：只要文档中出现敏感词中任意连续两个字的片段，即视为命中。" style="font-size: 0.75rem; color: #888; text-decoration: none; border: none; background: none;">
                                <span style="font-style: italic; text-decoration: underline;">模式说明</span>
                            </button>
                        </div>

                        <!-- 检测结果 -->
                        <div id="resultArea" class="mt-4" style="display: none;">
                            <h5>检测结果：</h5>
                            <div id="resultList"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/static/js/jquery-3.6.0.min.js}"></script>
    <script th:src="@{/static/js/bootstrap.bundle.min.js}"></script>
    <script>
        // 文件列表
        let selectedFiles = [];

        // 初始化拖拽上传
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('fileInput');
        const fileList = document.getElementById('fileList');
        const selectedFilesList = document.getElementById('selectedFiles');
        const detectBtn = document.getElementById('detectBtn');
        const resultArea = document.getElementById('resultArea');
        const resultList = document.getElementById('resultList');

        // 拖拽事件处理
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('border-primary');
        });

        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('border-primary');
        });

        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('border-primary');
            handleFiles(e.dataTransfer.files);
        });

        // 文件选择事件处理
        fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
        });

        // 处理选择的文件
        function handleFiles(files) {
            // 清空现有文件列表，只保留新拖拽或选择的文件
            selectedFiles = [];

            for (let file of files) {
                if (isValidFile(file)) {
                    selectedFiles.push(file);
                } else {
                    alert(`不支持的文件类型：${file.name}`);
                }
            }
            updateFileList();
        }

        // 检查文件类型
        function isValidFile(file) {
            const validTypes = [
                'text/plain',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'application/vnd.ms-excel',
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'application/pdf',
                'application/vnd.ms-powerpoint', // For .ppt files
                'application/vnd.openxmlformats-officedocument.presentationml.presentation' // For .pptx files
            ];
            return validTypes.includes(file.type);
        }

        // 更新文件列表显示
        function updateFileList() {
            if (selectedFiles.length > 0) {
                fileList.style.display = 'block';
                selectedFilesList.innerHTML = '';
                selectedFiles.forEach((file, index) => {
                    const li = document.createElement('li');
                    li.className = 'list-group-item d-flex justify-content-between align-items-center';
                    li.innerHTML = `
                        ${file.name}
                        <button class="btn btn-sm btn-danger" onclick="removeFile(${index})">
                            删除
                        </button>
                    `;
                    selectedFilesList.appendChild(li);
                });
                detectBtn.disabled = false;
            } else {
                fileList.style.display = 'none';
                detectBtn.disabled = true;
            }
        }

        // 删除文件
        function removeFile(index) {
            selectedFiles.splice(index, 1);
            updateFileList();
        }

        // 一键清除所有文件
        function clearAllFiles() {
            selectedFiles = [];
            updateFileList();
        }

        // 检测文件
        function detectFiles() {
            if (selectedFiles.length === 0) {
                return;
            }

            // 获取检测模式
            const mode = document.querySelector('input[name="detectMode"]:checked').value;
            console.log('[前端] 发起检测请求，模式:', mode, '文件数:', selectedFiles.length);

            // 显示加载动画
            detectBtn.disabled = true;
            detectBtn.innerHTML = `
                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                检测中...
            `;

            // 创建FormData对象
            const formData = new FormData();
            selectedFiles.forEach(file => {
                formData.append('files', file);
            });
            formData.append('mode', mode);

            // 发送请求
            $.ajax({
                url: '/detector/check',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(results) {
                    console.log('[前端] 检测请求成功，收到结果：', results);
                    displayResults(results);
                },
                error: function(xhr, status, error) {
                    console.error('[前端] 检测请求失败！状态：', status, '错误：', error, '响应：', xhr.responseText);
                    alert('检测失败，请稍后重试');
                },
                complete: function() {
                    console.log('[前端] 检测请求完成。');
                    // 恢复按钮状态
                    detectBtn.disabled = false;
                    detectBtn.innerHTML = '开始检测';
                }
            });
        }

        // 显示检测结果
        function displayResults(results) {
            resultArea.style.display = 'block';
            resultList.innerHTML = '';

            results.forEach(result => {
                const card = document.createElement('div');
                card.className = 'card mb-3';
                
                // 文件标题
                const title = document.createElement('div');
                title.className = 'file-title';
                title.textContent = result.fileName;
                card.appendChild(title);

                // 检测结果
                const body = document.createElement('div');
                body.className = 'card-body';

                if (result.errorMessage) {
                    body.innerHTML = `<div class="alert alert-danger">${result.errorMessage}</div>`;
                } else if (!result.hasSensitiveWords) {
                    body.innerHTML = '<div class="alert alert-success">未检测到敏感词</div>';
                } else {
                    // 显示敏感词上下文
                    result.sensitiveWordContexts.forEach(context => {
                        const item = document.createElement('div');
                        item.className = 'sensitive-word-item';
                        
                        // 敏感词标签
                        const labels = document.createElement('div');
                        labels.className = 'sensitive-word-row';
                        labels.innerHTML = `
                            <span class="result-label sensitive">敏感词: ${context.word}</span>
                            <span class="result-label position">位置: ${context.position}</span>
                        `;
                        item.appendChild(labels);

                        // 上下文
                        const contextDiv = document.createElement('div');
                        contextDiv.className = 'context-content';
                        // 高亮显示敏感词
                        const start = context.wordStartPos;
                        const end = context.wordEndPos;
                        const highlightedContext =
                            context.context.substring(0, start) +
                            `<span class="highlight">` +
                            context.context.substring(start, end) +
                            `</span>` +
                            context.context.substring(end);
                        contextDiv.innerHTML = highlightedContext;
                        item.appendChild(contextDiv);

                        body.appendChild(item);
                    });
                }

                card.appendChild(body);
                resultList.appendChild(card);
            });
        }

        // 初始化Bootstrap Popover
        document.addEventListener('DOMContentLoaded', function() {
            var helpBtn = document.getElementById('modeHelpBtn');
            if (helpBtn) {
                new bootstrap.Popover(helpBtn, {
                    html: true // 允许HTML内容，支持<br/>换行
                });
            }
        });
    </script>
</body>
</html> 